package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    //前置拦截方法：进入到控制器方法之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
//        //判断是否存在token
//        boolean verifyToken = JwtUtils.verifyToken(token);
//        //如果失效：拦截（返回状态码401）
//        if(!verifyToken) {
//            response.setStatus(401);
//            return false;
//        }
        //解析token，获取id和mobile
        Claims claims = JwtUtils.getClaims(token);
        Integer id  = (Integer) claims.get("id");
        String mobile = (String) claims.get("mobile");
        //构造User对象，存入Threadlocal
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        UserHolder.set(user);
        //如果正常：继续向后执行
        return true;
    }
}
